package com.example.a2205douyin.fragment;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.PagerSnapHelper;
import androidx.recyclerview.widget.RecyclerView;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.BounceInterpolator;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.example.a2205douyin.Live2Activity;
import com.example.a2205douyin.LiveActivity;
import com.example.a2205douyin.MainActivity;
import com.example.a2205douyin.R;
import com.example.a2205douyin.adapter.PinglunAdapter;
import com.example.a2205douyin.adapter.VideoTuiAdapter;
import com.example.a2205douyin.baseMVVM.view.BaseFragment;
import com.example.a2205douyin.databinding.FragmentTuijian2Binding;
import com.example.a2205douyin.db.AppDBUtils;
import com.example.a2205douyin.entity.PinglunEntity;
import com.example.a2205douyin.entity.ResultEntity;
import com.example.a2205douyin.entity.VideoEntity;
import com.example.a2205douyin.recommend.RecommendViewModel;
import com.example.a2205douyin.util.aspectj.CheckLogin;
import com.shuyu.gsyvideoplayer.GSYVideoManager;
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMVideo;

import java.util.ArrayList;
import java.util.List;


public class TuijianFragment extends BaseFragment<FragmentTuijian2Binding, RecommendViewModel> {

   List<VideoEntity.DataBean> videos = new ArrayList<>();
   VideoTuiAdapter videoTuiAdapter;
   int page = 1;
   int size = 30;
   int index;//接收当前播放的视频下标，后续使用
    long lastTime;//上次点击的时间

    List<PinglunEntity.DataBean> pingluns = new ArrayList<>();
    PinglunAdapter pinglunAdapter;

    public TuijianFragment() {
        // Required empty public constructor
    }


    @Override
    protected void initData() {
        viewModel.videoSuccess.observe(this, new Observer<VideoEntity>() {
            @Override
            public void onChanged(VideoEntity entity) {
                if(entity.getCode()==200){
                    videos.addAll(entity.getData());
                    videoTuiAdapter.notifyDataSetChanged();
                }else {
                    ToastUtils.showLong(entity.getMessage());
                }
            }
        });
        viewModel.videoFail.observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                ToastUtils.showLong(s);
            }
        });
        viewModel.guanSucc.observe(this, new Observer<ResultEntity>() {
            @Override
            public void onChanged(ResultEntity entity) {
                ToastUtils.showLong(entity.getMessage());
                if(entity.getCode()==200){
                    //更换图标---然后添加动画慢慢消失
                    ImageView ivAdd = (ImageView) videoTuiAdapter.getViewByPosition(index, R.id.iv_add);
                    ivAdd.setImageResource(R.drawable.ic_duigou);
                    ObjectAnimator animator = ObjectAnimator.ofFloat(ivAdd, "alpha", 1, 0);//透明度从1变成0
                    animator.setDuration(5000);//设置整个动画的时长
                    animator.start();//启动动画效果
                    videos.get(index).setGuanzhu(1);
                }
            }
        });
        viewModel.guanFail.observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                ToastUtils.showLong(s);
            }
        });
        //点赞取消点赞的监听
        viewModel.loveSucc.observe(this, new Observer<ResultEntity>() {
            @Override
            public void onChanged(ResultEntity entity) {
                ToastUtils.showLong(entity.getMessage());
                if(entity.getCode()==200){
                    //点赞图标发生变化，点赞数量发生变化
                    ImageView ivDianzan = (ImageView) videoTuiAdapter.getViewByPosition(index,R.id.iv_dianzan);
                    TextView tvDianzan = (TextView) videoTuiAdapter.getViewByPosition(index,R.id.tv_dianzan);
                    ivDianzan.setImageResource(R.drawable.ic_xihuanred);
                    tvDianzan.setText(videos.get(index).getLike_count()+1+"");
                    videos.get(index).setDianzan(1);
                    //添加动画效果
                    ObjectAnimator scaleX = ObjectAnimator.ofFloat(ivDianzan, "scaleX", 1, 2, 1);
                    ObjectAnimator scaleY = ObjectAnimator.ofFloat(ivDianzan, "scaleY", 1, 2, 1);
                    ObjectAnimator rotation = ObjectAnimator.ofFloat(ivDianzan, "rotation", -30, 30, 0);
                    AnimatorSet set = new AnimatorSet();
                    set.setDuration(2000);
                    set.play(scaleX).with(scaleY).with(rotation);
                    set.start();
                }
            }
        });
        viewModel.loveFail.observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                ToastUtils.showLong(s);
            }
        });

        viewModel.noloveSucc.observe(this, new Observer<ResultEntity>() {
            @Override
            public void onChanged(ResultEntity entity) {
                ToastUtils.showLong(entity.getMessage());
                if(entity.getCode()==200){
                    //点赞图标发生变化，点赞数量发生变化
                    ImageView ivDianzan = (ImageView) videoTuiAdapter.getViewByPosition(index,R.id.iv_dianzan);
                    TextView tvDianzan = (TextView) videoTuiAdapter.getViewByPosition(index,R.id.tv_dianzan);
                    ivDianzan.setImageResource(R.drawable.ic_xihuan);
                    tvDianzan.setText(videos.get(index).getLike_count()+"");
                    videos.get(index).setDianzan(0);
                }
            }
        });
        viewModel.noloveFail.observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                ToastUtils.showLong(s);
            }
        });
        viewModel.getSucc.observe(this, new Observer<PinglunEntity>() {
            @Override
            public void onChanged(PinglunEntity entity) {
                ToastUtils.showLong(entity.getMessage());
                if(entity.getCode()==200){
                    pingluns.clear();//清空原来的数据
                    pingluns.addAll(entity.getData());
                    pinglunAdapter.notifyDataSetChanged();
                }
            }
        });
        viewModel.getFail.observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                ToastUtils.showLong(s);
            }
        });
        viewModel.comSucc.observe(this, new Observer<PinglunEntity>() {
            @Override
            public void onChanged(PinglunEntity entity) {
                ToastUtils.showLong(entity.getMessage());
                if(entity.getCode()==200){
                    //获取返回值中的第一条数据   将这条数据添加到集合的最上方
                    PinglunEntity.DataBean bean = entity.getData().get(0);
                    pingluns.add(0,bean);
                    pinglunAdapter.notifyDataSetChanged();
                }
            }
        });
        viewModel.comFail.observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                ToastUtils.showLong(s);
            }
        });
    }

    @Override
    protected void initView() {
        videoTuiAdapter = new VideoTuiAdapter(videos);
        binding.rv.setAdapter(videoTuiAdapter);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        binding.rv.setLayoutManager(linearLayoutManager);

        viewModel.video(page,size);
        //分页优化
        PagerSnapHelper helper = new PagerSnapHelper();
        helper.attachToRecyclerView(binding.rv);
        //自动播放
        binding.rv.setOnScrollChangeListener(new View.OnScrollChangeListener() {
            @Override
            public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                int position = linearLayoutManager.findFirstVisibleItemPosition();
                index = position;
                StandardGSYVideoPlayer gsy = (StandardGSYVideoPlayer) videoTuiAdapter.getViewByPosition(position, R.id.gsy);
                if(gsy!=null){
                    gsy.startPlayLogic();
                }
            }
        });
        //添加子控件的点击事件
        videoTuiAdapter.addChildClickViewIds(R.id.iv_add,R.id.iv_dianzan,R.id.cl_full,R.id.iv_pinglun,R.id.iv_close,R.id.iv_fasong
                ,R.id.iv_fenxiang,R.id.iv_shoucang,R.id.cl_live);
        videoTuiAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                switch (view.getId()){
                    case R.id.iv_add:
                        guanzhu(position);
                        break;
                    case R.id.iv_dianzan:
                        dianzan(position);
                        break;
                    case R.id.cl_full:
                        full(position);
                        break;
                    case R.id.iv_pinglun:
                        //打开评论框
                        binding.rv.setIntercept(false);
                        open(position);
                        break;
                    case R.id.iv_close:
                        //关闭评论框
                        binding.rv.setIntercept(true);
                        close(position);
                        break;
                    case R.id.iv_fasong:
                        //发送评论
                        fasong(position);
                        break;
                    case R.id.iv_fenxiang:
                        fenxiang(position);//分享视频
                        break;
                    case R.id.iv_shoucang:
                        shoucang(position);//收藏视频
                        break;
                    case R.id.cl_live:
                        live(position);
                        break;
                }
            }
        });


    }

    private void live(int position) {
        //将整个DataBean 作为参数进行传递
        Intent intent = new Intent(getContext(), LiveActivity.class);
        intent.putExtra("video",videos.get(position));
        startActivity(intent);
        //这个是跳转到recyclerview版本的直播间
        /*Intent intent = new Intent(getContext(), Live2Activity.class);
        intent.putExtra("index",position);
        startActivity(intent);*/
    }

    private void shoucang(int position) {
        //查看是否收藏成功了，打印之前收藏的数据
        /*for (VideoEntity.DataBean bean : AppDBUtils.getInstance().getVideoDao().queryAll()) {
            Log.d("ssss", "shoucang: "+bean.getAuthname()+"------"+bean.getCaption());
        }*/

        AppDBUtils.getInstance().getVideoDao().insertVideo(videos.get(position));//将当前视频保存到数据库中了
        ToastUtils.showLong("收藏成功");
        ImageView iv = (ImageView) videoTuiAdapter.getViewByPosition(position,R.id.iv_shoucang);
        iv.setImageResource(R.drawable.ic_shoucangyellow);
    }

    private void fenxiang(int position) {
        UMVideo video =new UMVideo(videos.get(position).getVideopath());
        /*video.setTitle(videos.get(position).getCaption());//视频的标题
        UMImage image = new UMImage(getContext(),videos.get(position).getVideomainimg());
        video.setThumb(image);//视频的缩略图
        video.setDescription(videos.get(position).getCaption());//视频的描述*/
        new ShareAction(getActivity()).withMedia(video)
                .setDisplayList(SHARE_MEDIA.QQ,SHARE_MEDIA.WEIXIN)
                .setCallback(new UMShareListener() {
                    @Override
                    public void onStart(SHARE_MEDIA media) {

                    }

                    @Override
                    public void onResult(SHARE_MEDIA media) {
                        ToastUtils.showLong("分享成功");
                    }

                    @Override
                    public void onError(SHARE_MEDIA media, Throwable throwable) {
                        ToastUtils.showLong("分享失败"+throwable.getMessage());
                    }

                    @Override
                    public void onCancel(SHARE_MEDIA media) {
                        ToastUtils.showLong("取消了分享");
                    }
                })
                .open();
    }

    @CheckLogin
    private void fasong(int position) {
        //找到editText控件
        EditText etPinglun = (EditText) videoTuiAdapter.getViewByPosition(position, R.id.et_pinglun);
        String trim = etPinglun.getText().toString().trim();//trim() 去掉字符串 前后端的空格  字符串中间有空格不能去除
        if(trim.isEmpty()){
           ToastUtils.showLong("你还未输入任何有效的内容");
           return;
        }
        viewModel.comment(trim,videos.get(position).getId());

        etPinglun.setText("");
    }

    private void close(int position) {
        //评论框隐藏
        ConstraintLayout clPinglun = (ConstraintLayout) videoTuiAdapter.getViewByPosition(position, R.id.cl_pinglun);
        clPinglun.setVisibility(View.GONE);
        //隐藏动画
        Animation animation = AnimationUtils.loadAnimation(getContext(), R.anim.out);
        clPinglun.startAnimation(animation);
    }

    private void open(int position) {
        //评论框显示
        ConstraintLayout clPinglun = (ConstraintLayout) videoTuiAdapter.getViewByPosition(position, R.id.cl_pinglun);
        clPinglun.setVisibility(View.VISIBLE);
        //显示动画
        Animation animation = AnimationUtils.loadAnimation(getContext(), R.anim.in);
        animation.setInterpolator(new BounceInterpolator());
        clPinglun.startAnimation(animation);
        //展示评论数据
        //获取到展示的rv列表
        RecyclerView rvPing = (RecyclerView) videoTuiAdapter.getViewByPosition(position, R.id.rv_pinglun);
        pinglunAdapter = new PinglunAdapter(R.layout.item_pinglun,pingluns);
        rvPing.setAdapter(pinglunAdapter);
        rvPing.setLayoutManager(new LinearLayoutManager(getContext()));
        //执行后台请求
        viewModel.getComment(videos.get(position).getId());

    }

    //全屏观看
    private void full(int position) {
        //拿到播放器
        StandardGSYVideoPlayer gsy = (StandardGSYVideoPlayer) videoTuiAdapter.getViewByPosition(position, R.id.gsy);
        gsy.startWindowFullscreen(getContext(),false,false);//全屏播放
    }
    @CheckLogin
    private void dianzan(int position) {
        //如果出现连续点击的清空，我们默认第二次点击不触发方法
        if(System.currentTimeMillis()-lastTime<1000){
            lastTime = System.currentTimeMillis();//记录点击的时间
            return;
        }
        //先获取视频是否点赞过-
        int dianzan = videos.get(position).getDianzan();
        if(dianzan==0){//当前状态为未点赞   点击后，变成点赞效果
            viewModel.love(videos.get(position).getId());
        }else {//当前状态为已点赞   点击后，变成取消点赞效果
            viewModel.nolove(videos.get(position).getId());
        }
        lastTime = System.currentTimeMillis();//记录点击的时间
    }
    @CheckLogin
    private void guanzhu(int position) {
        viewModel.guanzhu(videos.get(position).getAuthname()+"");
    }

    @Override
    protected Class<RecommendViewModel> getViewModel() {
        return RecommendViewModel.class;
    }

    @Override
    protected int getLayout() {
        return R.layout.fragment_tuijian2;
    }
    //防止内存泄露
    //界面销毁时，释放所有视频资源
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        GSYVideoManager.releaseAllVideos();
    }

    @Override
    public void onResume() {
        super.onResume();
        GSYVideoManager.onResume(true);//继续播放
    }

    @Override
    public void onPause() {
        super.onPause();
        GSYVideoManager.onPause();
    }
}